
import '../sass/ShopDetail.scss'
import { useParams, useNavigate } from 'react-router-dom'
import { NavBar, Toast } from 'react-vant';
import axios from 'axios'
import { useEffect, useState } from 'react';
import { useSelector, useDispatch } from 'react-redux'
import { changeCount, changeIsShopbagCountLoad } from '../store/store'

function ShopDetail() {

    //数据
    let [ShopDetailData, setShopDetailData] = useState({ desc: [], rule: [] })
    let [count, setCount] = useState(1)
    let shopbagCount = useSelector(state => state.public.count)
    let isShopbagCountLoad = useSelector(state => state.public.shopbagCount)

    //导入方法
    let params = useParams()
    let navigate = useNavigate()
    let dispath = useDispatch()

    //方法
    let getData = pid => {
        axios({
            method: 'get',
            url: '/productDetail',
            params: {
                pid
            }
        }).then(res => {
            let result = res.data.result[0]
            result.desc = result.desc.split(/\n/);
            let ruleChoose = ['cream', 'milk', 'tem', 'sugar']
            let rule = []
            ruleChoose.forEach(item => {
                if (!result[item]) {
                    return
                }
                let currentRule = {
                    title: result[`${item}_desc`],
                    activeIndex: 0,
                    rule: []
                }
                let ruleItem = result[item].split('/')
                ruleItem.forEach(item => {
                    currentRule.rule.push({ title: item })
                })
                rule.push(currentRule)
            })
            result.rule = rule
            setShopDetailData(result)
        })
    }
    let goBack = () => {
        navigate(-1)
    }
    let ruleChoose = (item, index) => {
        item.activeIndex = index
        setShopDetailData({ ...ShopDetailData })
    }
    let reduceCount = () => {
        if (count > 1) {
            count--
            setCount(count)
        }
    }
    let addCount = () => {
        count++
        setCount(count)
    }
    let addToShopBag = () => {
        let rule = []
        ShopDetailData.rule.forEach(item => {
            let ruleTitle = item.rule[item.activeIndex].title
            rule.push(ruleTitle)
        })
        axios({
            method: 'post',
            url: '/addShopcart',
            data: {
                pid: params.id,
                count,
                rule: rule.join('/'),
            }
        }).then(res => {
            setTimeout(() => {
                Toast({
                    message: res.data.msg
                })
            }, 350)
            if (res.data.code == 700) {
                navigate('/login')
            }
            if (res.data.code == 3000) {
                getShopbagCount()
            }
        })
        
    }
    let getShopbagCount = () => {
		axios({
			method: 'get',
			url: '/findAllShopcart'
		}).then(res => {
			if (res.data.code==700) {
                dispath(changeCount(0))
                dispath(changeIsShopbagCountLoad(false))
            }else if (res.data.code==5000) {
                let totalCount = 0
				res.data.result.forEach(item => {
					totalCount += item.count
				})
				dispath(changeCount(totalCount))
                dispath(changeIsShopbagCountLoad(true))
            }
		})
	}

    //hook周期
    useEffect(() => {
        getData(params.id)
        if (!isShopbagCountLoad) {
            getShopbagCount()
        }
    }, [])

    return (
        <div className="ShopDetail">
            <NavBar
                title="商品详情"
                leftText="返回"
                onClickLeft={() => { goBack() }}
            />
            <div className="imgbox">
                <img className='auto-img' src={ShopDetailData.large_img} alt="" />
            </div>
            <div className="shop-message-box">
                <div className="shop-message">
                    <div className="name-box">
                        <div className="name">{ShopDetailData.name}</div>
                        <div className="enname">{ShopDetailData.enname}</div>
                    </div>
                    <div className="price">¥{ShopDetailData.price}</div>
                </div>
                <div className="rule-box">
                    {
                        ShopDetailData.rule.map((item, index) => {
                            return (
                                <div className="rule" key={index}>
                                    <div className="rule-title">{item.title}</div>
                                    <div className="rule-list">
                                        {item.rule.map((item2, index2) => {
                                            return (
                                                <div className={`rule-list-item ${item.activeIndex == index2 ? 'active' : ''}`} key={index2} onClick={() => ruleChoose(item, index2)}>
                                                    {item2.title}
                                                </div>
                                            )
                                        })}
                                    </div>
                                </div>
                            )
                        })
                    }
                </div>
                <div className="count-box">
                    <div className="count-box-title">选择数量</div>
                    <div className="count-box-count">
                        <div className="reduce-btn" onClick={() => { reduceCount() }}>-</div>
                        <div className="count">{count}</div>
                        <div className="add-btn" onClick={() => { addCount() }}>+</div>
                    </div>
                </div>
                <div className="desc-title">商品描述</div>
                <div className="desc-box">
                    {
                        ShopDetailData.desc.map((item, index) => {
                            return (
                                <div className="desc-list" key={index}>
                                    {index + 1}、{item}
                                </div>
                            )
                        })
                    }
                </div>
            </div>
            <div className="bottom-nav">
                <div className="shopbag" onClick={() => { navigate('/shopbag') }}>
                    <div className="shopbag-icon"><span className="iconfont icon-24gf-bag"></span></div>
                    <div className="shopbag-title">购物袋</div>
                    {shopbagCount > 0 && <div className={`shopbag-count ${shopbagCount<10?'style10':''}`}>{shopbagCount}</div>}
                </div>
                <div className="collect">
                    <div className="collect-icon"><span className="iconfont icon-icon-"></span></div>
                    <div className="collect-title">收藏</div>
                </div>
                <div className="add-shopbag" onClick={() => { addToShopBag() }}>加入购物袋</div>
            </div>
        </div>
    )
}
export default ShopDetail